<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    v-loading="loading"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('1000px')"
    :visible="visible"
    :title="title + $t('ASSOCIATED_SERVICE')"
    :append-to-body="true"
    class="segment-dialog"
    @open="open"
    @close="close"
  >
    <div class="flex flex-wrap dialog-detail">
      <template v-if="associatedData.associatedType === 'device'">
        <!-- <div class="w-50 flex align-center">
          <span class="title-label">{{ $t('DEVICE_NAME') }}:</span>
          {{ associatedData.nodeName }}
        </div> -->
        <div class="w-50">
          <span class="title-label">{{ $t('BELONGS_REGION_STATION_NAME') }}:</span>
          {{ getRegionName(associatedData.stationId) }}
        </div>
        <div class="w-50">
          <span class="title-label">{{ $t('BELONGS_ROOM_NAME') }}:</span>
          {{ getRegionName(associatedData.roomId, 'room') }}
        </div>
      </template>
      <template v-else>
        <!-- <div class="w-100 flex align-center">
          <span class="title-label">{{ $t('CABLE_NAME') }}:</span>
          {{ associatedData.label }}
        </div> -->
        <div class="w-50">
          <span class="title-label">{{ $t('A_END_REGION_STATION') }}:</span>
          {{ getRegionName(associatedData.fromNodeId) }}
        </div>
        <div class="w-50">
          <span class="title-label">{{ $t('Z_END_REGION_STATION') }}:</span>
          {{ getRegionName(associatedData.toNodeId) }}
        </div>
      </template>
    </div>
    <el-table
      ref="AssociatedBizTable"
      class="associated-biz-table"
      :data="tableData"
      :span-method="spanMethod"
      size="mini"
      height="100%"
      border
      align="center"
    >
      <template slot="empty">
        <NullData />
      </template>
      <el-table-column type="index" :label="$t('SEQUENCE')" :width="resetSize(60)" />
      <el-table-column
        v-if="associatedData.associatedType === 'cable'"
        prop="fiberName"
        :label="$t('FIBER_CORE')"
        width="180"
      />
      <template v-else>
        <el-table-column :label="$t('PORT_NAME')" prop="portName" />
      </template>
      <el-table-column :label="$t('SERVICE_NAME')" prop="bizOpen.bizName" />
      <el-table-column :label="$t('BIZ_STATUS')" prop="bizStatus">
        <template slot-scope="scope">
          <div v-html="getContent(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <template v-slot:footer>
      <el-button @click="close">{{ $t('CLOSE') }}</el-button>
    </template>
  </el-dialog>
</template>
<script>
  import { mapGetters } from 'vuex'
  import homeApi from '@/api/oen/HomeApi'
  import { getParentsById } from '@/utils/common'
  import { handleServiceI18n } from '@/service/i18n'
  export default {
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      associatedData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        loading: false,
        bizList: [],
        tableData: []
      }
    },
    computed: {
      ...mapGetters(['regionTree', 'dictMap']),
      title() {
        console.log('this.associatedData', this.associatedData)
        return this.associatedData.nodeName || this.associatedData.label
      }
    },
    created() {
      this.open()
    },
    methods: {
      async open() {
        console.log('open', this.associatedData)
        this.loading = true
        // return
        const res = await (this.associatedData.associatedType === 'cable'
          ? homeApi.getByCableId({ cableId: this.associatedData.cableId })
          : homeApi.getByNodeId({ nodeId: this.associatedData.nodeId }))
        this.loading = false
        this.bizList = res || []
        if (this.associatedData.associatedType === 'cable') {
          this.getDetailByCableId()
        } else {
          this.getDetailByNodeId()
        }
      },
      getContent(row) {
        const statusSort = [
          'FAULT',
          'OPEN_FAIL',
          'RESTORE_FAIL',
          'REDUCTION_FAIL',
          'RETURN_FAIL',
          'OPENING',
          'RESTORING',
          'RETURNING',
          'RESTORE',
          'NORMAL'
        ]
        const statusColor = [
          {
            value: 'fault',
            keys: ['FAULT']
          },
          {
            value: 'doing',
            keys: [
              'OPENING',
              'RESTORING',
              'RETURNING',
              'OPEN_FAIL',
              'RESTORE_FAIL',
              'REDUCTION_FAIL',
              'RETURN_FAIL'
            ]
          },
          {
            value: 'normal',
            keys: ['RESTORE', 'NORMAL']
          }
        ]
        const statusIndex = row.bizOpen.bizChannelList.map(z =>
          statusSort.findIndex(j => j === z.bizStatus)
        )
        const bizStatus = statusSort[Math.min(...statusIndex)]
        const colorData = statusColor.find(i => i.keys.includes(bizStatus))
        return `<span class="color-${colorData ? colorData.value : 'normal'}">${
          this.dictMap.BIZ_STATUS[bizStatus]
        }</span>`
      },
      getDetailByNodeId() {
        this.bizList.forEach(biz => {
          if (!biz.segmentChannelList) return
          const portNameList = []
          biz.segmentChannelList.forEach((channel) => {
            const port = {}
            if (channel.startNodeId === this.associatedData.nodeId) {
              port.portName = handleServiceI18n(channel.startPort.portName)
              port.connPortName = handleServiceI18n(channel.startPort.connPortName)
            }
            if (channel.endNodeId === this.associatedData.nodeId) {
              port.portName = handleServiceI18n(channel.endPort.portName)
              port.connPortName = handleServiceI18n(channel.endPort.connPortName)
            }
            // 判断连接关系是否已经存在了
            const hasSamePort = portNameList.some(i => {
              return (i.portName === port.portName && i.connPortName === port.connPortName) ||
                (i.portName === port.connPortName && i.connPortName === port.portName)
            })
            if (!hasSamePort) portNameList.push(port)
          })
          const portNameListUnique = portNameList.map((i, index) => {
            return {
              portName: i.connPortName ? i.portName + '，' + i.connPortName : i.portName,
              bizOpen: biz.bizOpen,
              rowSpan: index === 0 ? portNameList.length : 0
            }
          })
          this.tableData.push(...portNameListUnique)
        })
      },
      getDetailByCableId() {
        this.bizList.forEach(biz => {
          if (!biz.segmentChannelList) return
          biz.segmentChannelList.forEach((channel, index) => {
            if (channel.fiberId && channel.fiber.cableId === this.associatedData.cableId) {
              const port = {}
              port.fiberName = channel.fiber.fiberName
              port.bizOpen = biz.bizOpen
              port.rowSpan = index === 0 ? biz.segmentChannelList.length : 0
              this.tableData.push(port)
            }
          })
        })
      },
      spanMethod({ row, column, rowIndex, columnIndex }) {
        // console.log(row, column, rowIndex, columnIndex)
        if (columnIndex === 2 || columnIndex === 3) {
          return [row.rowSpan, 1]
        }
      },
      getRegionName(regionId, regionType) {
        if (!regionId) return '--'
        const regionList = (getParentsById(this.regionTree, regionId, 'regionId') || [])
          .reverse()
          .map((i) => i.regionName)
        if (regionType === 'room' || regionType === 'station') {
          return regionList[regionList.length - 1]
        }
        if (!regionType) {
          return regionList.join('/')
        }
      },
      close() {
        this.$emit('close', false)
      }
    }
  }
</script>
<style lang="scss">
  @import '@/assets/css/mixin.module.scss';
  .associated-biz-table {
    .color-fault {
      @include themeify {
        color: themed('bizFault');
      }
    }
    .color-doing {
      @include themeify {
        color: themed('bizDoing');
      }
    }
    .color-normal {
      @include themeify {
        color: themed('bizNormal');
      }
    }
  }
</style>
